package com.abai.doubi.server.controller;

import cn.hutool.core.bean.BeanUtil;
import com.abai.doubi.entity.Result;
import com.abai.doubi.entity.dto.RoleCreateDTO;
import com.abai.doubi.entity.dto.RoleSearchDTO;
import com.abai.doubi.entity.dto.RoleSkillCreateDTO;
import com.abai.doubi.entity.pojo.Role;
import com.abai.doubi.entity.pojo.RoleSkill;
import com.abai.doubi.entity.vo.RoleVO;
import com.abai.doubi.server.service.IRoleService;
import com.abai.doubi.server.service.IRoleSkillService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

//@CrossOrigin("*")
@RestController
@RequestMapping("/role")
@Tag(name = "角色接口", description = "角色相关接口")
@Slf4j
public class RoleController {
    @Autowired
    private IRoleService roleService;

    @Autowired
    private IRoleSkillService roleSkillService;

    /**
     * 创建角色
     * POST /role/create
     */
    @PostMapping("/create")
    @Operation(summary = "创建角色", description = "管理员创建新角色")
    public Result createRole(@Parameter(description = "角色信息", required = true) @RequestBody RoleCreateDTO roleCreateDTO) {
        // 1. 参数校验
        if (roleCreateDTO == null) {
            return Result.error("角色信息不能为空");
        }

        if (StringUtils.isBlank(roleCreateDTO.getRoleName())) {
            return Result.error("角色名称不能为空");
        }

        if (StringUtils.isBlank(roleCreateDTO.getCategory())) {
            return Result.error("角色分类不能为空");
        }

        // 2. 检查角色是否已存在
        Role existingRole = roleService.lambdaQuery()
                .eq(Role::getRoleName, roleCreateDTO.getRoleName())
                .one();

        if (existingRole != null) {
            return Result.error("角色名称已存在");
        }

        // 3. 设置默认值
        if (roleCreateDTO.getStatus() == null) {
            roleCreateDTO.setStatus(1); // 默认启用状态
        }
        Role role = BeanUtil.copyProperties(roleCreateDTO, Role.class);
        // 4. 保存角色
        boolean saved = roleService.save(role);

        if (saved) {
            return Result.success("角色创建成功");
        } else {
            return Result.error("角色创建失败");
        }
    }

    /**
     * 搜索角色列表
     * GET /role/search
     */
    @PostMapping("/search")
    @Operation(summary = "搜索角色", description = "根据关键词和分类搜索角色")
    public Result<List<Role>> searchRoles(@RequestBody RoleSearchDTO roleSearchDTO) {
        // 实现搜索逻辑
        // 1. 根据关键词模糊搜索角色名称、描述等字段
        // 2. 根据分类筛选角色
        // 3. 分页返回结果
        String keyword = roleSearchDTO.getKeyword();
        String category = roleSearchDTO.getCategory();
        Integer pageNum = roleSearchDTO.getPageNum();
        Integer pageSize = roleSearchDTO.getPageSize();
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(keyword)){
            queryWrapper.like(Role::getRoleName, keyword)
                    .or()
                    .like(Role::getDescription, keyword);
        }
        if (StringUtils.isNotBlank(category)){
            queryWrapper.like(Role::getCategory, category);
        }
        Page<Role> page = roleService.page(new Page<>(pageNum,pageSize),queryWrapper);
        return Result.<List<Role>>builder()
                .code(Result.SUCCESS_CODE)
                .data(page.getRecords())
                .build();
    }

    /**
     * 获取角色分类列表
     * GET /role/categories
     */
    @GetMapping("/categories")
    @Operation(summary = "获取角色分类", description = "获取所有角色分类")
    public Result<List<String>> getRoleCategories() {
        // 实现获取所有角色分类的逻辑
        // 例如：历史人物、文学角色、商业领袖、影视明星等
        List<String> categories = roleService.lambdaQuery()
                .select(Role::getCategory)
                .groupBy(Role::getCategory)
                .list()
                .stream()
                .map(Role::getCategory)
                .collect(Collectors.toList());
        return Result.<List<String>>builder()
                .code(Result.SUCCESS_CODE)
                .data(categories)
                .build();
    }

    /**
     * 获取热门角色列表
     * GET /role/hot
     */
    @GetMapping("/hot")
    @Operation(summary = "获取热门角色", description = "获取热门推荐角色列表")
    @Parameter(name = "count", description = "数量", in = ParameterIn.QUERY, schema = @Schema(defaultValue = "10"))
    public Result<List<Role>> getHotRoles(@RequestParam(defaultValue = "10") Integer count) {

        // 实现获取热门角色的逻辑
        // 可以根据使用次数、评分等排序（使用redis缓存，rabbitMQ异步存储到mysql）

        return Result.success("获取热门角色成功");
    }

    /**
     * 获取角色详情
     * GET /role/{id}
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取角色详情", description = "根据角色ID获取详细信息")
    @Parameter(name = "id", description = "角色ID", in = ParameterIn.PATH, required = true)
    public Result<RoleVO> getRoleDetail(@PathVariable Long id) {
        // 实现获取角色详情的逻辑,返回角色信息，包括技能列表
        Role role = roleService.getById(id);
        if (role == null){
            return Result.error("角色不存在");
        }
        List<RoleSkill> roleSkills = roleSkillService.lambdaQuery().eq(RoleSkill::getRoleId, id).list();
        RoleVO roleVO = BeanUtil.copyProperties(role, RoleVO.class);
        roleVO.setRoleSkills(roleSkills);
        return Result.<RoleVO>builder()
                .code(Result.SUCCESS_CODE)
                .data(roleVO)
                .build();

    }

    /**
     * 获取角色技能列表
     * GET /role/{id}/skills
     */
    @GetMapping("/skills/{id}")
    @Operation(summary = "获取角色技能", description = "根据角色ID获取角色技能列表")
    @Parameter(name = "id", description = "角色ID", in = ParameterIn.PATH, required = true)
    public Result<List<RoleSkill>> getRoleSkills(@PathVariable Long id) {
        // 实现获取角色技能列表的逻辑
        if(id == null){
            return Result.error("角色ID不能为空");
        }
        List<RoleSkill> roleSkills = roleSkillService.lambdaQuery()
                .eq(RoleSkill::getRoleId, id)
                .list();
        return Result.<List<RoleSkill>>builder()
                .code(Result.SUCCESS_CODE)
                .data(roleSkills)
                .build();
    }

    /**
     * 获取角色技能列表
     * Post /role/{id}/skills
     */
    @PostMapping("/skills")
    @Operation(summary = "创建角色技能", description = "为指定角色创建技能")
    public Result<List<RoleSkill>> addRoleSkills(@Parameter(description = "角色技能信息", required = true) @RequestBody RoleSkillCreateDTO roleSkillCreateDTO) {
        // 实现获取角色技能列表的逻辑
        if (roleSkillCreateDTO.getRoleId() == null){
            return Result.error("角色ID不能为空");
        }
        if (StringUtils.isAnyBlank(roleSkillCreateDTO.getSkillName(),roleSkillCreateDTO.getTriggerKeywords(),roleSkillCreateDTO.getSkillTemplate())){
            return Result.error("技能名称、触发关键词、技能模板不能为空");
        }
        RoleSkill roleSkill = BeanUtil.copyProperties(roleSkillCreateDTO, RoleSkill.class);
        roleSkillService.save(roleSkill);
        return Result.success("角色技能创建成功");
    }
}
